<template>
  <div class="good_list">
    <el-scrollbar
      ref="scrollArea"
      class="scroll-container"
      @scroll="handleScroll"
    >
      <el-table
        :data="tableData"
        style="width: 100%; height: 100%; overflow-y: scroll"
      >
        <el-table-column fixed prop="date" label="Date" width="150" />
        <el-table-column prop="name" label="Name" width="120" />
        <el-table-column prop="state" label="State" width="120" />
        <el-table-column prop="city" label="City" width="120" />
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default>
            <el-button link type="primary" size="small" @click="handleClick">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from "vue";
import { ElScrollbar } from "element-plus";

const scrollArea = ref<InstanceType<typeof ElScrollbar> | null>(null);
let isLoading = false; // 防止重复请求的标志

const handleClick = () => {
  console.log("click");
};

// 处理滚动事件
const handleScroll = () => {
  const container = scrollArea.value?.wrapRef;
  if (container && !isLoading) {
    const threshold = 20; // 阈值，可以根据实际情况调整
    if (
      container.scrollHeight - container.scrollTop - threshold <=
      container.clientHeight
    ) {
      loadMoreData(); // 触发加载更多数据
    }
  }
};

// 加载更多数据
const loadMoreData = () => {
  if (isLoading) return;
  isLoading = true;

  setTimeout(() => {
    const newData = [
      {
        date: "2024-05-03",
        name: "好大一只",
        state: "California",
        city: "Los Angeles",
      },
      // 添加更多数据项
    ];
    tableData.value = [...tableData.value, ...newData];
    isLoading = false;

    nextTick(() => {
      // 触发下一轮的滚动检查
      handleScroll();
    });
  }, 1000);
};

const tableData = ref<
  Array<{
    date: string;
    name: string;
    state: string;
    city: string;
  }>
>([
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  {
    date: "2016-05-03",
    name: "Tom",
    state: "California",
    city: "Los Angeles",
  },
  // 添加初始数据
]);
</script>
<style lang="scss" scoped>
.good_list {
  width: 100%;
}
</style>
